package ci.web.router;

import java.lang.reflect.Constructor;

import ci.web.annotaction.Inner;
import ci.web.annotaction.Limiter;
import ci.web.annotaction.Router;
import ci.web.core.CiContext;
import ci.web.core.CiRequest;
import ci.web.core.CiResponse;

/**
 * 利用构造函数做处理
 * @author zhh
 */
public class CiConstructorHandler extends CiHandler {

    public CiConstructorHandler(String pkg, Constructor<?> method){
        super(pkg, method);
    }
    
    @Override
    protected String methodName() {
        return "/";
    }

    @Override
    public String toString() {
        return String.format("{p:%s, j:%s.%s}", path, className(), "()");
    }
    
    /**
     * 寻找符合Ci构造函数的路由
     * @param clazz
     * @return
     */
    public static CiHandler tryMake(Class<?> clazz, String packageName) {
    	if(clazz.getAnnotation(Inner.class)!=null){
    		return null;
    	}
    	Constructor<?>[] cs = clazz.getConstructors();
        for(Constructor<?> constructor : cs){
        	//必须有ci-注释信息/ci请求参数，才会被扫描 而且只取一个
        	if(constructor.getAnnotation(Inner.class)!=null){
        		continue;
        	}
        	Class<?>[] types = constructor.getParameterTypes();
        	if(constructor.getAnnotation(Router.class)==null && constructor.getAnnotation(Limiter.class)==null){
        		boolean had = false;
        		for(int i=0; i<types.length; i++){
                    Class<?> type = types[i];
                    if(type==CiRequest.class || type==CiResponse.class || type==CiContext.class){
                    	had = true;
                    	break;
                    }
                }
        		if(had==false){
        			continue;
        		}
        	}
        	if(check(constructor)){
                return new CiConstructorHandler(packageName, constructor);
            }
        }
        return null;
    }
    
}
